package com.mrx.bot.telegram.utils;

import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Mr.X
 * @since 2025/6/14 14:09
 */
@Setter
public class WebmToGifConverter {

    private String ffmpegPath = "ffmpeg";

    private int fps = 23;

    private int width = 320;

    private double cropDetectThreshold = 0.1;

    private static final Logger logger = LoggerFactory.getLogger(WebmToGifConverter.class);

    public void convertWebmToGif(String inputFile, String outputFile) throws IOException, InterruptedException {
        logger.info("开始处理: {}", inputFile);
        // 检测裁剪参数
        String cropParams = detectCropParams(inputFile);
        if (cropParams == null) {
            logger.info("无法检测到裁剪参数, 使用原始尺寸");
        } else {
            logger.info("检测到的裁剪参数: crop={}", cropParams);
        }
        // 转换为 GIF
        convertToGif(inputFile, outputFile, cropParams);
    }

    private String detectCropParams(String inputFile) throws IOException, InterruptedException {
        List<String> command = new ArrayList<>();
        command.add(ffmpegPath);
        command.add("-i");
        command.add(inputFile);
        command.add("-vf");
        command.add(String.format("format=gray,negate,cropdetect=%.1f:16:0", cropDetectThreshold));
        command.add("-f");
        command.add("null");
        command.add("-");
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        String lastCropParams = null;
        Pattern cropPattern = Pattern.compile("crop=(\\d+:\\d+:\\d+:\\d+)");
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Matcher matcher = cropPattern.matcher(line);
                if (matcher.find()) {
                    lastCropParams = matcher.group(1);
                }
            }
        }
        process.waitFor();
        return lastCropParams;
    }

    private void convertToGif(String inputFile, String outputFile, String cropParams) throws IOException, InterruptedException {
        StringBuilder filterBuilder = new StringBuilder();
        // 添加裁剪参数（如果有）
        if (cropParams != null) {
            filterBuilder.append("crop=").append(cropParams).append(",");
        }
        // 添加其他滤镜
        filterBuilder.append(String.format("fps=%d,scale=%d:-1:flags=lanczos,", fps, width));
        filterBuilder.append("split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse");
        List<String> command = new ArrayList<>();
        command.add(ffmpegPath);
        command.add("-i");
        command.add(inputFile);
        command.add("-vf");
        command.add(filterBuilder.toString());
        command.add("-y");
        command.add(outputFile);
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        Process process = pb.start();
        // 实时显示进度
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            Pattern progressPattern = Pattern.compile("time=(\\d+:\\d+:\\d+\\.\\d+)");
            while ((line = reader.readLine()) != null) {
                Matcher matcher = progressPattern.matcher(line);
                if (matcher.find()) {
                    System.out.print("\r进度: " + matcher.group(1));
                }
            }
        }
        int exitCode = process.waitFor();
        System.out.println(); // 换行
        if (exitCode == 0) {
            File output = new File(outputFile);
            logger.info("转换成功, 输出文件: {}, 文件大小: {}", outputFile, (output.length() / 1024) + " KB");
        } else {
            logger.error("转换失败, 错误码: {}", exitCode);
        }
    }

}